package App.Controller;

import App.Model.BaseEnum;
import App.Model.BaseResponse;
import App.Model.User;
import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Created by xw on 2018/11/12.
 */
//@RestController
public class BaseController {

    /*
    public  void OnActionExecuting(ActionExecutingContext context)
    {
    }



    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleException(MethodArgumentNotValidException exception) {

        String errorMsg = exception.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .findFirst()
                .orElse(exception.getMessage());

        return ErrorResponse.builder().message(errorMsg).build();
    }
    */

    public BaseResponse ResponseError(Object obj, String message) {

        BaseResponse _baseResponse = new BaseResponse();
        _baseResponse.setMessage(message);
        _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());
        _baseResponse.setData(obj);
        return _baseResponse;

    }

    //获取登陆用户id
    public int userId() {
        int _userId = 0;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {
            String _princile = auth.getPrincipal().toString();
            if (_princile != null && _princile != "") {
                User _user = JSON.parseObject(_princile, User.class);
                if (_user != null) {
                    _userId = _user.getId();
                }
            }
        }
        return _userId;
    }


    public String userName() {
        Authentication auth = SecurityContextHolder.getContext()
                .getAuthentication();
        String domain = null;
        if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {

            String _princile = auth.getPrincipal().toString();
            User uu = JSON.parseObject(_princile, User.class);
            //User user = (User) ;
            // domain = user.getUsername();
            domain = uu.getPassword();


        }
        return domain;
        //return Optional.ofNullable(domain);
    }
}

